using UnityEngine;
using System.Collections;

public class InputManager : MonoBehaviour 
{
	public GameObject lastGameObject;
	
	void Update()
	{
		if(Input.touchCount == 1 && Input.touches[0].phase == TouchPhase.Ended)
		{
			if(startRaycast())
			{
				gameObject.SendMessage("OnTouchUp",startRaycast(),SendMessageOptions.DontRequireReceiver);
			}
		}
		
		if(Input.touchCount == 1 && Input.touches[0].phase == TouchPhase.Began)
		{
			if(startRaycast())
			{
				gameObject.SendMessage("OnTouchDown",startRaycast(),SendMessageOptions.DontRequireReceiver);
			}
		}
		
		if(Input.touchCount == 1)
		{
			if(!lastGameObject)
			{
				if(startRaycast())
				{
					lastGameObject = startRaycast();
					gameObject.SendMessage("OnTouchEnter",lastGameObject,SendMessageOptions.DontRequireReceiver);
				}
			}
			else if(startRaycast())
			{
				if(lastGameObject != startRaycast())
				{
					gameObject.SendMessage("OnTouchExit",lastGameObject,SendMessageOptions.DontRequireReceiver);
					gameObject.SendMessage("OnTouchEnter",startRaycast(),SendMessageOptions.DontRequireReceiver);
					lastGameObject = startRaycast();
				}
				else
				{
					gameObject.SendMessage("OnTouchOver",lastGameObject,SendMessageOptions.DontRequireReceiver);
				}
			}
			else
			{
				gameObject.SendMessage("OnTouchExit",lastGameObject,SendMessageOptions.DontRequireReceiver);
				lastGameObject = null;
			}
		}
		else if(lastGameObject)
		{
			gameObject.SendMessage("OnTouchExit",lastGameObject,SendMessageOptions.DontRequireReceiver);
			lastGameObject = null;
		}
		
	}
	
	private GameObject startRaycast()
	{
		Ray ray = Camera.mainCamera.ScreenPointToRay(new Vector3(Input.touches[0].position.x, Input.touches[0].position.y, 0f));
		RaycastHit hit;
		
		if (Physics.Raycast(ray, out hit, Mathf.Infinity))
		{
			return hit.collider.gameObject;
		}
		
		return null;
	}
}
